import EleResize from '@/utils/resize-event.js'
// const echarts = require('echarts/dist/echarts.common.min')
class Chartutil {
  constructor() {
    this.option = {
      title: {
        show: true,
        left: '2%',
        text: '',
        textStyle: {
          color: '#37474f',
          fontStyle: 'normal',
          fontWeight: 'normal',
          fontFamily: '微软雅黑',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        x: 100,
        x2: 80,
        y2: 80
      },
      // xAxis: [],
      // yAxis: [],
      // legend: {},
      // toolbox: {
      //   show: false,
      //   feature: {
      //     mark: { show: true },
      //     dataView: { show: true, readOnly: false },
      //     magicType: {
      //       show: true,
      //       type: ['pie', 'funnel']
      //     }
      //   }
      // },
      calculable: false,
      series: []
    }
  }
  /**
   * @name categoryBar
   * @description 渐变折线图
   */
  categoryBar(params) {
    let { cb = () => {}, _this, dom,xAxis, XData, YData, linecolor, jiancolor, series, legend, color, unit,rotate = 0, grid = { x: 40, y2: 60, x2: 40 },dataZoom} = params;
    let option = {
      color: color,
      // grid: {
      //   top: '15%',
      //   left: '0%',
      //   bottom: '8%',
      //   containLabel: true,
      // },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: [{
        type: 'category',
        boundaryGap: false,
        axisLine: { //坐标轴轴线相关设置。数学上的x轴
          show: true,
          lineStyle: {
            color: '#CFDAE5'
          },
        },
        axisLabel: { //坐标轴刻度标签的相关设置
          textStyle: {
            color: '#7E8386',
            margin: 15,
          },
          interval:0,
          rotate: rotate
        },
        axisTick: { show: false, },
        // data: XData,
        data: [],
      }],
      yAxis: [{
        type: 'value',
        min: 0,
        // max: max,
        splitNumber: 7,
        splitLine: {
          show: true,
          lineStyle: {
            color: '#CFDAE5'
          }
        },
        axisLine: { show: false, },
        axisLabel: {
          margin: 20,
          textStyle: {
            color: '#777',

          },
        },
        axisTick: { show: false, },
      }],

      dataZoom: dataZoom,
      if (grid) {
        options.grid = grid
      },
      series: series ? series : [{
        name: '',
        type: 'line',
        smooth: true, //是否平滑曲线显示
        symbolSize: 4,
        color:[linecolor],  //折线条的颜色
        lineStyle: {
          normal: {
            color: linecolor  // 线条颜色
          }
        },
        areaStyle: { //区域填充样式
          normal: {
            //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: jiancolor },
              { offset: 1, color: '#ffffff' }
            ], false),
            shadowColor: 'rgba(53,142,215, 0.1)', //阴影颜色
            shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
          }
        },
        data: YData
      }]
    }
    unit ? (option.yAxis[0].name = '（' + (unit || '') + '）') : null;
    Object.assign(option, {
      legend: legend,
      xAxis: xAxis,
    })
    
    this.drawAndResize(_this, dom, option, cb);
  }
  drawPie(params) {
    const commonColor = [
      '#50a5f6',
      '#00d897',
      '#fea858',
      '#FF8A8A',
      '#FFC533',
      '#ff8a80',
      '#7f6aff',
      '#ffc533',
      '#ff5da3',
      '#00cfda',
      '#c1aea8',
      '#a7d778',
      '#9aa8d0',
      '#4699ff',
      '#00d897',
      '#fea858',
      '#ff8a8a',
      '#7f6aff',
      '#ffc533',
      '#ff589c',
      '#00cfda',
      '#9aa8d0',
      '#a7d778',
     
    ]
    let options = JSON.parse(JSON.stringify(this.option));
    let {
      _this,
      dom,
      unit, // 单位
      legend, // 图例
      series, // series
      color, // 颜色
    } = params
    if (legend !== undefined) {
      if (Array.isArray(legend)) {
        Object.assign(options, {
          legend: {
            x: 'right',
            y: 40,
            orient: 'vertical',
            align: 'left',
            data: legend.map((item) => {
              return {
                name: item,
                icon: 'circle',
              }
            }),
            formatter: function (name) {
              var data = options.series[0].data;
              var total = 0;
              var tarValue;
              for (var i = 0, l = data.length; i < l; i++) {
                total += data[i].value;
                if (data[i].name == name) {
                  tarValue = data[i].value;
                }
              }
              var p = (tarValue / total * 100).toFixed(1);
              return name;
              // return name + ' ' + '(' + p + '%)';				

            }
          }
        }) && (series[0].label = { show: false }) && (series[0].labelLine = { show: false })
      } else {
        Object.assign(options, {
          legend: legend
        })
      }
    }
    Object.assign(options, {
      series: series,
    })

    color ? options.color = color : options.color = commonColor
    this.drawAndResize(_this, dom, options)
  }
  /**
 * @name drawGauge
 * @description 仪表盘图
 * @author wqy
 * @date 2020-04-30 13:46:20
 * @param {} _this 
 * @param {*} dom 
 * @param {*} options 
 */
  drawGauge(params) {
    let { _this, dom, title, value, valueColor, linearColor } = params;
    let option = {
      legend: {
        show: false
      },
      grid: {
        z: 1,    //grid作为柱状图的坐标系，其层级要和仪表图层级不同，同时隐藏
        show: false,
        left: '-30%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
        splitLine: {
          show: false    //隐藏分割线
        },
      },
      xAxis: [   //这里有很多的show，必须都设置成不显
        {
          type: 'category',
          data: [],
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
          splitArea: {
            interval: 'auto',
            show: false
          }
        }
      ],
      yAxis: [ //这里有很多的show，必须都设置成不显示
        {
          type: 'value',
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
        }
      ],
      toolbox: {
        show: false,
      },
      series: [
        {
          name: '刻度盘',
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          center: ["50%", "65%"], //整体的位置设置
          z: 3,
          min: 0,
          max: 200,
          splitNumber: 10,
          radius: '90%',
          axisLine: {            // 坐标轴线
            lineStyle: {       // 属性lineStyle控制线条样式
              width: 16,
              color: [[0.5,  new _this.$echarts.graphic.LinearGradient(
                  0, 0, 1, 0,
                  [
                    { offset: 0, color: linearColor[0] },
                    { offset: 1, color: linearColor[1] }
                  ]
                )], [1,  new _this.$echarts.graphic.LinearGradient(
                  0, 0, 1, 0,
                  [
                    { offset: 0, color: linearColor[2] },
                    { offset: 1, color: linearColor[3] }
                  ]
                )]]
            }
          },
          axisTick: {            // 坐标轴小标记
            length: 19,        // 属性length控制线长
            splitNumber: 2,
            lineStyle: {       // 属性lineStyle控制线条样式
              color: '#cdcdcd'
            }
          },
          splitLine: {           // 分隔线
            length: 20,         // 属性length控制线长
            lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
              color: 'auto'
            }
          },
          axisLabel: {
            textStyle: {
              color: '#454A57'
            }
          },
          pointer: {
            show: true,
            length: '70%',
            width: 5,
          },
          itemStyle: {
            normal: {
              color: '#454A57',
              borderWidth: 0
            }
          },
          title: {   //仪表盘标题
            text: title,
            show: true,
            offsetCenter: ['0', '54'],
            textStyle: {
              color: '#798384',
              fontSize: 12,
              fontFamily: 'Microsoft YaHei'
            }
          },
          detail: {
            textStyle: {
              fontSize: 14,
              color: valueColor
            },
            offsetCenter: ["0%", "27"],
            formatter: (a) => {
              return a + '%';
            }
          },
          data: [{ value: value, name: title }]
        }
      ]
    }
    this.drawAndResize(_this, dom, option);
  }
  /**
   * @name drawRadar
   * @description 雷达图
   * @author cjs1992
   * @date 2019-01-24 09:42
   */
  drawRadar(params) {
    /**
     * data 后台接口返回数据
     */
    let { cb = () => { }, data, _this, dom, legend, indicator, series } = params;
    let options = JSON.parse(JSON.stringify(this.option));
    // 静态页面雷达图
    const Roption = {
      // title: {
      //     text: '基础雷达图'
      // },
      tooltip: {},
      legend: {
        data: legend,
        y: 'bottom'
      },
      radar: {
        shape: 'circle',
        name: {
          textStyle: {
            // color: '#fff',
            // backgroundColor: '#999',
            borderRadius: 3,
            padding: [3, 5]
          }
        },
        indicator: indicator,
        radius: '65%',
        center: ['50%', '45%']
      },
      series: series
    };
    Object.assign(options, { ...Roption })
    this.drawAndResize(_this, dom, options);
  }
  drawBar(params) {
    let commonColor = [
      '#6aa0e6',
      "#3fb1e3",
      "#6be6c1",
      "#febf8f",
      "#a0a7e6",
      "#c4ebad",
      "#96dee8",
    ]
    /**
     * _this:  this对象，获取$echarts用
     * dom: 渲染的dom对象
     * series: series
     * legend: 图例, 对象或者数组
     * title: 标题
     * color: 颜色
     * xAxis: x轴
     * yAxis： y轴
     * gradient: 是否渐变
     * option: 配置项
     * grid: grid
     * unit: 单位
     * legend_top: legend top
     * barBorderRadius  bar图的borderRadius
     */
    let { legend_top = 0, _this, dom, istwo, series, legend, title, color, xAxis, yAxis, gradient, dataZoom, option, grid = { x: 40, y2: 60, x2: 40 }, unit = '', rotate = 0, barBorderRadius = 0 } = params
    let options = JSON.parse(JSON.stringify(this.option))

    // xAxis
    let xAxis_ = [
      {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: '#777'
          }
        },
        axisLabel: {
          interval: 0,
          rotate: rotate
        },
        // data: xdata
        data: []
      }
    ]
    let yAxis_ = [
      {
        type: 'value',
        minInterval: 1,
        axisLine: { show: false },
        axisTick: { show: false },
        // axisLabel: {
        //   formatter: '{value} ' + unit
        // }
      }
    ]
    unit ? (yAxis_[0].name = '（' + (unit || '') + '）') : null
    if (dataZoom) {
      options.dataZoom = dataZoom
    }
    title !== undefined ? options.title.text = title : options.title.show = false
    /**
     * legend: []
     * 默认居于右上，水平放置
     */
    if (Array.isArray(legend)) {
      options.legend = {
        data: legend,
        right: 0,
        top: legend_top,
        type: 'scroll',
        orient: 'horizontal'
      }
    } else {
      if (legend) {
        options.legend = legend
      }
    }

    /**
     * 判断是x轴或者y轴
     */
    if (yAxis && !istwo) {
      xAxis_[0].data = yAxis
      options.xAxis = yAxis_
      options.yAxis = xAxis_
    } else {
      xAxis_[0].data = xAxis
      options.xAxis = xAxis_
      options.yAxis = yAxis_
    }
    if (yAxis && istwo) {
      options.yAxis = yAxis
    }
    if (grid) {
      options.grid = grid
    }
    if (gradient) {
      /**
       * 当gradient为true时，默认颜色满足我需要的,即[[],[],[]]
       */
      for (let i = 0, j = color.length; i < j; i++) {
        let arr = []
        if (color[i].length === 3) {
          arr = [
            { offset: 0, color: color[i][0] },
            { offset: 0.5, color: color[i][1] },
            { offset: 1, color: color[i][2] }
          ]
        } else {
          arr = [
            { offset: 0, color: color[i][0] },
            { offset: 1, color: color[i][1] }
          ]
        }
        if (series.length > 1) {
          // 判断渐变方向
          let ar = [0, 0, 0, 1]
          if (yAxis) {
            ar = [0, 0, 1, 0]
          }
          // 多条
          if (series[i].itemStyle) {
            series[i].itemStyle.color = new _this.$echarts.graphic.LinearGradient(
              ...ar,
              arr
            )
          } else {
            series[i].itemStyle = {
              color: new _this.$echarts.graphic.LinearGradient(
                ...ar,
                arr
              )
            }
          }
        } else {
          // 单条
          let num = series[0].data[i]
          series[0].data[i] = {
            name: xAxis[i],
            value: num,
            itemStyle: {
              color: new _this.$echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                arr
              )
            }
          }
        }
      }
    } else {
      if (color) {
        if (color.length >= series.length) {
          for (let i = 0, j = series.length; i < j; i++) {
            if (series[i].itemStyle) {
              series[i].itemStyle.color = color[i]
            } else {
              series[i].itemStyle = {
                color: color[i]
              }
            }
          }
        }
      } else {
        // if (color.length === series[0].data.length) {
        //   for (let i = 0, len = series[0].data.length; i < len; i++) {
        //     if (series[0].data[i].name) {
        //       if (series[0].data[i].itemStyle) {
        //         series[0].data[i].itemStyle['color'] = color[i]
        //       } else {
        //         series[0].data[i].itemStyle = {
        //           color: color[i]
        //         }
        //       }
        //     } else {
        //       series[0].data[i] = {
        //         name: yAxis ? yAxis[i] : xAxis[i],
        //         value: series[0].data[i],
        //         itemStyle: {
        //           color: color[i]
        //         }
        //       }
        //     }
        //   }
        // } else {
        options.color = commonColor
        // }
      }
    }
    for (let item of series) {
      if (item.itemStyle) {
        item.itemStyle.barBorderRadius = barBorderRadius
      } else {
        item.itemStyle = {
          barBorderRadius: barBorderRadius
        }
      }
    }
    options.series = series
    Object.assign(options, option)
    return this.drawAndResize(_this, dom, options)
  }
  /**
   * @name drawAndResize
   * @description 画图和绑定resize
   * @author cjs1992
   */
  drawAndResize(_this, dom, options,cb) {
    try {
      let myChart = _this.$echarts.init(dom);
      cb || (cb = function () {})
      myChart.off('click')
      myChart.on('click', cb)
      myChart.clear();
      myChart.setOption(options)
      /**
       * 改变事件
       */
      EleResize.on(dom, function () {
        myChart.resize()
      });
      return myChart;
    } catch (error) {
      console.log(error)
    }
    // window.addEventListener('resize', () => {
    //   myChart.resize();
    // })
  }
}
// export const $echarts = echarts
export const ChartUtil = new Chartutil()
